﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Web;
using MDF.Utilites.Helper;
using MDF.Cacher.Managements;
using MDF.Requesting;
using MDF.Logger.Managements;
using System.Globalization;
using TGVR.DataHelper.BussinessLogic.BookingSystem;
using TGVR.DataHelper.BussinessObject.BookingSystem;
using TGVR.DataHelper.BussinessObject;

namespace TGVR_Boot
{
    public class AirAsianBoot : IBoot
    {
        //1: nguoi lon, 2: tre em, 3: tre so sinh
        Requester m_request = new Requester();
        string viewstate = "";
        string debugid = "";
        string HidenData = "";

        string strCurrency = "5028700466";

        public string GetError()
        {
            return m_error;
        }
        private DateTime HoldToDate;
        public DateTime GetHoldToDate()
        {
            return HoldToDate;
        }

        #region Search Method

        public List<BK_Ticket> Search(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
          int _iAdut, int _iChild, int _iBaby, bool _isInter, int _iUserID)
        {

            string strKeyword = "AirAsianBoot" + _strStationForm + _strStationTo + _dtDateFrom.ToString("MMddyyyyhhmm") +
                (_dtDateTo.HasValue ? _dtDateTo.Value.ToString("MMddyyyyhhmm") : "") + _iAdut.ToString() + _iChild.ToString() + _iBaby.ToString() + "_User" + _iUserID;
            //m_log.Info("Search: " + strKeyword);
            var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            if (cacheResult != null)
            {
                //m_log.Info("Get from cache");
                return (List<BK_Ticket>)cacheResult;
            }

            Requester rq = new Requester();

            //var resHome = rq.GetData("http://www.airasia.com/vn/vi/home.page");
            //string strHtmlHome = rq.GetHtmlFromResponse(resHome);
            //HtmlDocument doc = new HtmlDocument();
            //doc.LoadHtml(strHtmlHome);
            ////<option value="5027992464">US Dollar (USD)</option>
            //var currency = doc.DocumentNode.SelectNodes("//*/option[contains(text(),'US Dollar (USD)')]");
            //if (currency != null && currency.Count > 0)
            //{
            //    strCurrency = currency[0].Attributes["value"].Value;
            //}
            //else
            //{
            //    LogManager.GetInstance().Error("Asia: Cant get currency");
            //}

            string strReturnDay = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("%d") : "";
            string strReturnMonth = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("%M") : "0";
            string strReturnYear = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("yyyy-%M") : "0";
            string strRound = _dtDateTo.HasValue ? "RoundTrip" : "OneWay";

            string strTemp = string.Format("ControlGroupCompactView%24AvailabilitySearchInputCompactView%24RadioButtonMarketStructure={0}&ControlGroupCompactView_AvailabilitySearchInputCompactVieworiginStation1={1}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24TextBoxMarketOrigin1={1}&ControlGroupCompactView_AvailabilitySearchInputCompactViewdestinationStation1={2}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24TextBoxMarketDestination1={2}&ControlGroupCompactView%24MCCControlCompactSearchView%24DropDownListCurrencies=&ControlGroupCompactView%24MultiCurrencyConversionViewCompactSearchView%24DropDownListCurrency=" + strCurrency + "&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListMarketDay1={3}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListMarketMonth1={4}-{5}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListMarketDay2={6}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListMarketMonth2={7}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListPassengerType_ADT={9}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListPassengerType_CHD={10}&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListPassengerType_INFANT={11}&__EVENTTARGET=&__EVENTARGUMENT=&pageToken=&culture=vi-VN&promocode=&ControlGroupCompactView%24ButtonSubmit=Search&ControlGroupCompactView%24AvailabilitySearchInputCompactView%24DropDownListSearchBy=columnView",
                strRound,//0
                _strStationForm,//1
                _strStationTo,//2
                _dtDateFrom.ToString("dd"),//3
                _dtDateFrom.ToString("yyyy"),//4
                _dtDateFrom.ToString("MM"),//5
                strReturnDay,//6
                strReturnYear,//7
                strReturnMonth,//8
                _iAdut,//9
                _iChild,//10
                _iBaby//11
                );

            var respone = rq.PostData("http://booking.airasia.com/Compact.aspx", strTemp);
            string htmlRespone = rq.GetHtmlFromResponse(respone);

            var result = GetFromHTML(htmlRespone, _strStationForm, _strStationTo, _dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby, _iUserID);

            if (result != null && result.Count > 0)
            {
                CacheManager.GetInstance().Add(strKeyword, result.ToList());
            }

            return result;
        }

        public List<BK_Ticket> GetFromHTML(string htmlRespone, string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo, int _iAdut, int _iChild, int _iBaby, int _iUserID)
        {
            List<BK_Ticket> lstResult = new List<BK_Ticket>();
            if (!string.IsNullOrEmpty(htmlRespone))
            {

                //if (resResult != null)
                {
                    //string htmlResult = rq.GetHtmlFromResponse(resResult);
                    HtmlDocument doc = new HtmlDocument();
                    doc.LoadHtml(htmlRespone);
                    //kiểm tra xem đúng chuyến bay không?
                    string strFlights = "";
                    try
                    {
                        strFlights = doc.DocumentNode.SelectNodes("//*[@class=\"depart-section\"]")[0].InnerText;
                    }
                    catch
                    {
                        return lstResult;
                    }
                    if (strFlights == null)
                    {
                        return lstResult;
                    }

                    //kiểm tra tìm vé không thành công
                    var travles = doc.DocumentNode.SelectNodes("//*[@class=\"depart-section\"]");
                    if (travles == null)
                    {
                        return lstResult;
                    }
                    var iFeeTGVR = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "FeeAirAsian").Value);
                    var iDollar = decimal.Parse(SettingBUS.Current.GetSetting(_iUserID, "TyGiaAsia1").Value);

                    decimal iDollarHold24h = decimal.Parse(SettingBUS.Current.GetSetting(_iUserID, "TyGiaAsiaHold24h").Value);
                    

                    decimal FeeBookQuickly48 = 1;
                    var FeeServiceAsia = decimal.Parse(SettingBUS.Current.GetSetting(_iUserID, "FeeServiceAsia").Value);
                    var FeeServiceAsiaUSD = decimal.Parse(SettingBUS.Current.GetSetting(_iUserID, "FeeServiceAsiaUSD").Value);
                    int AsiaOneWayFee = (int)(decimal.Parse(SettingBUS.Current.GetSetting(_iUserID, "AsiaOneWayFee").Value) * iDollar);
                    decimal exchange = 1;

                    //FlightDate < 5ngay
                    if (_dtDateFrom.AddDays(-5) > DateTime.Now && (_strStationForm == "SGN" || _strStationForm == "HAN" || _strStationForm == "DAD"))
                    {
                        iDollar = iDollarHold24h;
                        FeeServiceAsia = FeeServiceAsiaUSD * iDollar;
                    }

                    else
                    {

                        if (_dtDateFrom.AddDays(-2) < DateTime.Now)
                        {
                            //>48h: 
                            //{[ (web  * (tỷ giá1+ chenhlech) * phi quan ly giao dich   + TGVR fee + phụ thsu xuất vé airasia}
                            //chenhlech = 0,phi quan ly giao dich = 1,phụ thu xuất vé airasia /=3
                            iDollar = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "TyGiaAsia2").Value);
                            FeeBookQuickly48 = decimal.Parse(SettingBUS.Current.GetSetting(_iUserID, "FeeBookQuickly48").Value);
                        }
                        else
                        {
                            int iNotBaby = _iAdut + _iChild;
                            FeeServiceAsia = FeeServiceAsia / iNotBaby;
                        }

                    }
                    if (_dtDateTo.HasValue)
                        FeeServiceAsia = FeeServiceAsia / 2;

                    if (travles != null && travles.Count > 0)
                    {
                        //từng lượt
                        int i = 0;
                        foreach (var travel in travles)
                        {

                            HtmlDocument docDepart = new HtmlDocument();
                            docDepart.LoadHtml(travel.InnerHtml);
                            //var tickets = docDepart.DocumentNode.SelectNodes("//input[@type=\"radio\"]");//gridTravelOptRet
                            var tickets = docDepart.DocumentNode.SelectNodes("//*[@class=\"rgRow\"]");//gridTravelOptRet

                            if (tickets == null)
                                continue;
                            //từng vé
                            for (int j = 0; j < tickets.Count; j++)// ; ticket in tickets)
                            {
                                HtmlDocument docTicket = new HtmlDocument();
                                docTicket.LoadHtml(tickets[j].InnerHtml);

                                string value = docTicket.DocumentNode.SelectNodes("//input[@type=\"radio\"]")[0].Attributes["value"].Value;
                                if (i == 0)
                                {
                                    //validate
                                    if (value.IndexOf(_strStationForm) == -1
                                        || value.IndexOf(_strStationTo) == -1
                                        || value.IndexOf(_dtDateFrom.ToString("MM/dd/yyyy")) == -1
                                        )
                                    {
                                        continue;
                                    }
                                }
                                else
                                {
                                    //validate
                                    if (value.IndexOf(_strStationForm) == -1
                                        || value.IndexOf(_strStationTo) == -1
                                        || value.IndexOf(_dtDateTo.Value.ToString("MM/dd/yyyy")) == -1
                                        )
                                    {
                                        continue;
                                    }
                                }
                                var priceClect = docTicket.DocumentNode.SelectNodes("//*[@class=\"price\"]");
                                if (priceClect == null)
                                {
                                    LogManager.GetInstance().Error("Asia: Can not get price");
                                    continue;
                                }
                                var strPriceFull = priceClect[priceClect.Count == 3 ? 1 : 0].InnerText.Split(' ');
                                LogManager.GetInstance().Debug("Currency = " + priceClect[priceClect.Count == 3 ? 1 : 0].InnerText);
                                if (strPriceFull[1] == "THB")
                                {
                                    decimal tempTHB = 645.16m;
                                    // d9oi63 sang USD
                                    exchange = tempTHB / iDollar;
                                    LogManager.GetInstance().Debug("exchange = " + exchange);
                                }
                                string strPrice = strPriceFull[0];//price
                                //strPrice = strPrice.Substring(0, strPrice.IndexOf(' '));
                                strPrice = strPrice.Replace(",", "");
                                decimal iPrice = decimal.Parse(strPrice);

                                LogManager.GetInstance().Debug("Currency = " + iPrice);
                                iPrice *= exchange;
                                //        0                    1                2                                     3                                      
                                //[1~W~W00H00~AAB1] [2~^2~Q~Q01H00H~AAX1] [13~X|AK~1451~ ] [SGN~02/22/2014 10:35~KUL~02/22/2014 13:25~^D7~ 316~ ] 
                                //                               4
                                //[KUL~02/22/2014 19:10~PEK~02/23/2014 01:15~@2/22/2014 03:35:00]

                                string[] arrTemp = value.Replace("~~", "_").Split('_');
                                string strFightNo = "";
                                try
                                {
                                    strFightNo = arrTemp[2].Split('|')[1].Replace("~", "").Trim();//FlightNo
                                }
                                catch
                                {
                                    strFightNo = arrTemp[1].Split('|')[1].Replace("~", "").Trim();//FlightNo
                                }

                                BK_Ticket ticket = new BK_Ticket();
                                ticket.Profit = (int)(iFeeTGVR * iDollar);
                                ticket.AirType = "airasia";
                                ticket.FeeOneWay = AsiaOneWayFee;
                                ticket.Path = new List<BK_Ticket>();

                                for (int iTicket = 3; iTicket < arrTemp.Length; iTicket++)
                                {
                                    BK_Ticket t = new BK_Ticket();
                                    t.Profit = (int)(iFeeTGVR * iDollar);
                                    t.AirType = "airasia";
                                    string[] strTemp1 = arrTemp[iTicket].Split('~');

                                    t.HoldToDate = DateTime.Now.AddHours(2);
                                    t.DataToBook = value;
                                    t.StartDate = DateTime.ParseExact(strTemp1[1], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                    t.EndDate = DateTime.ParseExact(strTemp1[3], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                    t.FlightNo = strFightNo;
                                    t.PriceBefore = (int)(iPrice * iDollar);
                                    //t.Price = iPrice + iFeeTGVR;
                                    //{[ (web  * (tỷ giá1+ chenhlech) * phi quan ly giao dich   + TGVR fee + phụ thsu xuất vé airasia}
                                    t.Price = (int)Math.Round(iPrice * iDollar * FeeBookQuickly48 + iFeeTGVR + FeeServiceAsia);

                                    t.FromCity = strTemp1[0];
                                    t.ToCity = strTemp1[2];

                                    t.LastUpdate = DateTime.Now;

                                    if (t.FromCity == _strStationForm)
                                        t.TypeWay = "Out";

                                    if (_dtDateTo.HasValue && t.FromCity == _strStationTo)
                                        t.TypeWay = "In";

                                    t.Image = "http://thegioivere.net/content/images/logo/" + t.FlightNo.Substring(0, 2) + ".png";

                                    if (!ticket.Path.Exists(m => m.StartDate.ToString("MM/dd/yyyy HH:mm") == t.StartDate.ToString("MM/dd/yyyy HH:mm")))
                                    {
                                        ticket.Path.Add(t);
                                    }

                                }
                                if (arrTemp.Length == 3)
                                {
                                    BK_Ticket t = ticket;
                                    t.Profit = (int)(iFeeTGVR * iDollar);
                                    t.HoldToDate = DateTime.Now.AddHours(2);
                                    string[] strTemp1 = arrTemp[2].Split('~');
                                    t.AirType = "airasia";
                                    t.DataToBook = value;
                                    t.StartDate = DateTime.ParseExact(strTemp1[1], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                    t.EndDate = DateTime.ParseExact(strTemp1[3], "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
                                    t.FlightNo = strFightNo;
                                    t.PriceBefore = (int)(iPrice * iDollar);
                                    t.Price = (int)Math.Round(iPrice * iDollar * FeeBookQuickly48 + iFeeTGVR + FeeServiceAsia);

                                    t.FromCity = strTemp1[0];
                                    t.ToCity = strTemp1[2];

                                    t.LastUpdate = DateTime.Now;

                                    if (i == 0)
                                    {
                                        t.TypeWay = "Out";
                                    }
                                    if (i == 1)
                                    {
                                        t.TypeWay = "In";
                                    }
                                    t.Image = "http://thegioivere.net/content/images/logo/" + t.FlightNo.Substring(0, 2) + ".png";
                                }
                                if (ticket.Path.Count > 0)
                                {
                                    ticket.HoldToDate = DateTime.Now.AddHours(2);
                                    ticket.DataToBook = ticket.Path[0].DataToBook;
                                    ticket.EndDate = ticket.Path[ticket.Path.Count - 1].EndDate;
                                    ticket.StartDate = ticket.Path[0].StartDate;
                                    ticket.DetailLink = ticket.Path[0].DetailLink;
                                    ticket.FlightNo = ticket.Path[0].FlightNo;
                                    ticket.FromCity = ticket.Path[0].FromCity;
                                    ticket.Image = ticket.Path[0].Image;
                                    ticket.LastUpdate = ticket.Path[0].LastUpdate;
                                    ticket.Price = ticket.Path[0].Price;
                                    ticket.PriceBefore = ticket.Path[0].PriceBefore;
                                    ticket.ReturnDate = ticket.Path[0].ReturnDate;
                                    ticket.ToCity = ticket.Path[ticket.Path.Count - 1].ToCity;
                                    ticket.TypeWay = ticket.Path[0].TypeWay;
                                }
                                if (!lstResult.Exists(m => m.StartDate.ToString("MM/dd/yyyy HH:mm") == ticket.StartDate.ToString("MM/dd/yyyy HH:mm")))
                                {
                                    lstResult.Add(ticket);
                                }
                            }
                            i++;
                        }
                    }
                    return lstResult;
                }
            }
            return lstResult;
        }

        public List<BK_Ticket> SearchCheapest(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDataTo,
              int _iAdut, int _iChild, int _iBaby, int _iUserID)
        {
            return null;
        }

        #endregion

        void XuLy(string html)
        {
            try
            {
                HtmlDocument docDepart = new HtmlDocument();
                docDepart.LoadHtml(html);
                var nodesviewstate = docDepart.DocumentNode.SelectNodes("//*[@id=\"__VIEWSTATE\"]");
                var notedebugid = docDepart.DocumentNode.SelectNodes("//*[@id=\"DebugID\"]");
                viewstate = HttpUtility.UrlEncode(nodesviewstate[0].Attributes["value"].Value);
                debugid = notedebugid[0].Attributes["value"].Value;
            }
            catch
            { }
        }
        public string resnumber = "";
        public string thanhtien = "";
        private string m_error;
        /// <summary>
        /// Lấy mã vé
        /// </summary>
        /// <returns></returns>
        public string GetCode()
        {
            if (string.IsNullOrEmpty(m_strReferrence))
                return string.Format("{0}", resnumber);
            return string.Format("{0}({1})", resnumber, m_strReferrence);
        }
        /// <summary>
        /// Lấy tổng tiền
        /// </summary>
        /// <returns></returns>
        public int GetTotal()
        {
            try
            {
                if (!string.IsNullOrEmpty(thanhtien))
                    return Int32.Parse(thanhtien.Replace(".", ""));
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("Asia: Cant get total price!", ex);
            }

            return 0;
        }

        public void GetRealData(string html)
        {
            try
            {
                HtmlDocument docDepart = new HtmlDocument();
                docDepart.LoadHtml(html);
                HidenData = docDepart.DocumentNode.SelectNodes("//*[@name=\"HiddenFieldPageBookingData\"]")[0].Attributes["value"].Value;
                if (HidenData.Length == 6)
                {
                    //Paylater
                    //<input type="hidden" name="HoldDateTime" value="20140708T18:51">

                    if (isCanPayLater)
                    {

                        resnumber = HidenData;
                        string strTime = docDepart.DocumentNode.SelectNodes("//*[@name=\"HoldDateTime\"]")[0].Attributes["value"].Value;
                        strTime = strTime.Replace("T", " ");
                        HoldToDate = DateTime.ParseExact(strTime, "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
                        thanhtien = docDepart.DocumentNode.SelectNodes("//*[@name=\"CovPayAmt\"]")[0].Attributes["value"].Value;
                        //id=ContentPlaceHolder1_lblPNR
                        //LogManager.GetInstance().Debug(html);
                        m_strReferrence = docDepart.DocumentNode.SelectNodes("//*[@name=\"NumRec\"]")[0].Attributes["value"].Value;
                    }
                    else
                    {

                        //Pay for agent
                        resnumber = HidenData;
                        thanhtien = docDepart.DocumentNode.SelectNodes("//*[@name=\"TxnAmount\"]")[0].Attributes["value"].Value;
                        thanhtien = thanhtien.Substring(0, thanhtien.IndexOf("."));

                    }

                }
                viewstate = docDepart.DocumentNode.SelectNodes("//*[@id=\"viewState\"]")[0].Attributes["value"].Value;
            }
            catch
            { }

        }

        void GetResNumber(string html)
        {
            HtmlDocument docDepart = new HtmlDocument();
            docDepart.LoadHtml(html);
            var nodesresnumber = docDepart.DocumentNode.SelectNodes("//*[@class=\"ResNumber\"]");
            resnumber = nodesresnumber[0].InnerText;
            //var nodestotalmoney = docDepart.DocumentNode.SelectNodes("//*[@class=\"ChargesTotal\"]//td[2]");

            thanhtien = docDepart.DocumentNode.SelectNodes("//*[@class=\"ChargesTotal\"]//td[2]")[0].InnerText.Replace(",", "");
            //*[@id="ContentPlaceHolder1_lblHold"]
            //thanhtien = docDepart.DocumentNode.SelectNodes("//*[@id=\"ContentPlaceHolder1_lblHold\"]")[0].InnerText.Replace(",", "");

        }
        public Dictionary<string, string> lstResultHTML = new Dictionary<string, string>();
        private string m_strReferrence;
        private bool isCanPayLater;

        public int MakeBooking(BK_Booking booking, BK_Passenger[] passenges, BK_Ticket tkDepart, BK_Ticket tkReturn, int _iUserID)
        {
            bool isBackReturnToDepart = false;
            if (tkDepart == null && tkReturn != null)//2 chieu # hang
            {
                isBackReturnToDepart = true;
                tkDepart = tkReturn;
                tkReturn = null;
            }
            HoldToDate = DateTime.Now.AddHours(2);
            string strEmailDefault = "thegioivere@gmail.com";
            int iDayTimeOut = Int32.Parse(SettingBUS.Current.GetSetting(_iUserID, "TimeoutBookAsia").Value);

            if (tkDepart.StartDate.AddHours(iDayTimeOut) <= DateTime.Now)
            {
                m_error = "Quá hạn book vé";
                return (int)BookingStatus.OUTOFBOOKING;
            }

            booking.Email = strEmailDefault;

            #region 1.Đăng nhập
            string strLinkLogin = "https://member.airasia.com/login.aspx?culture=en-GB";
            //string strData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=NgVhXgJ8wHoPzKKVS2WrmAmvwnTJjQHhh6oabJnZMzEebSk0ZEquUG%2BL%2FlusGa2qNGm%2Bv7fmgKbVuLNbOrMSLAV2bNO3kI8ZYh7FJJV1jY89xEUUJx0b%2BFrgWhGU5O5r3W6H1CUh5ZRCKDdFbMN0jQEDk4AwaLTw1zat2i9qY4Lx9LTLoHCfFGUMy%2FPGQnhfgs5Uo3z6ivv2zT7OTxlLYBZtTap01uY9C1FNq36a%2FA5tUHpxHoYTAcKYO0bY2DBwEJyIiVV4HiPg%2FmZd1oQIXrZCPSH4z1KJPbgSQ8%2Fun1TLLsd2BaaLTPIysNFJCgAe%2BIkrQxI5z6Szg6pa0e4WivsfZmzzWSksNXE0jdMnwNUaMciBJ%2FdRjBfVL2pkMZbFNtxNlpu77YbwjIoCwtbltcFVLdYYc2ZSGL%2BdFlYQVCJp8hdq&__VIEWSTATEENCRYPTED=&ctl00%24body%24txtUsername=vuthanhlinh2000%40gmail.com&ctl00%24body%24txtPassword=LINH2007&ctl00%24body%24chkRememberMe=on&ctl00%24body%24btnLogin=Login";
            //string strData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=586FY%2Ba8K11SY93G9rn9wqdL2AKwueoGuMXDW93EH%2BUAaC7QlzhFyPJU%2Fs%2FIqpugzRI3wszxdRWk2AG872Pjp%2Bjb%2FwEf6fV4OzBBLZkhxMkA0BN8cweZMIg19EnwYgXbHUU7e5BJsNUeIv2m66FU7ALHm1sGcGx3eIkfdPJ%2BpFD5uc7NksYA1CIqnozp%2FnxvUMaqMYSXzoso1iKOAdVdUHNlz9g%3D&__VIEWSTATEENCRYPTED=&ctl00%24body%24txtUsername=vuthanhlinh2000%40gmail.com&ctl00%24body%24txtPassword=LINH2007&ctl00%24body%24chkRememberMe=on&ctl00%24body%24btnLogin=%C4%90%C4%83ng+nh%E1%BA%ADp";
            string strData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=Hs2%2FOKq%2Bohr%2BZmCSTlriy%2F3SzAKfzPl%2Bd29Tp91l5HMnH46%2B%2FW%2Bhay4V3mLAGbu7aWr1pe%2BUfjJdT9d1OskNuzET7Y7XgJK79atN1EQ4mdckKpSYJgPAcdCI%2FjYmHmLiX93xoIXp0dcdLkW4dvyhIYkykW5nNNo%2FYg7DU4Y4oBO7BgwrneIkLoPAJcTFXnCQYWx3DIurAl0M0HXTa6J%2Bucu2ORQ%3D&__VIEWSTATEENCRYPTED=&ctl00%24body%24txtUsername=vuthanhlinh2000%40gmail.com&ctl00%24body%24txtPassword=Linh2008&ctl00%24body%24chkRememberMe=on&ctl00%24body%24btnLogin=Login";

            var resLogin = m_request.PostData(strLinkLogin, strData);
            string htmkHome = m_request.GetHtmlFromResponse(resLogin);
            lstResultHTML[strLinkLogin] = htmkHome;
            if (htmkHome.IndexOf("logoutLink") == -1)
            {
                this.SaveHTML(booking, lstResultHTML);
                throw new Exception("asia: Không thể đăng nhập");
            }

            #endregion

            #region 2.Search tickets

            string strReturnDay = tkReturn != null ? tkReturn.StartDate.ToString("%d") : "";
            string strReturnMonth = tkReturn != null ? tkReturn.StartDate.ToString("%M") : "0";
            string strReturnYear = tkReturn != null ? tkReturn.StartDate.ToString("yyyy") : "0";
            string strRound = tkReturn != null ? "RoundTrip" : "OneWay&oneWayOnly=1";

            int iAdut = passenges.Count(m => m.TypeID == 1);
            int iChild = passenges.Count(m => m.TypeID == 2);
            int iBaby = passenges.Count(m => m.TypeID == 3);

            strData = string.Format("__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUBMGRktapVDbdzjtpmxtfJuRZPDMU9XYk%3D&pageToken=&MemberLoginSearchView%24HFTimeZone=420&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24RadioButtonMarketStructure={0}&ControlGroupSearchView_AvailabilitySearchInputSearchVieworiginStation1={1}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24TextBoxMarketOrigin1={1}&ControlGroupSearchView_AvailabilitySearchInputSearchViewdestinationStation1={2}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24TextBoxMarketDestination1={2}&ControlGroupSearchView%24MultiCurrencyConversionViewSearchView%24DropDownListCurrency=" + strCurrency + "&date_picker={4}%2F{3}%2F{5}&date_picker=&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketDay1={3}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketMonth1={5}-{4}&date_picker={7}%2F{6}%2F{8}&date_picker=&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketDay2={6}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketMonth2={8}-{7}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListPassengerType_ADT={9}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListPassengerType_CHD={10}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListPassengerType_INFANT={11}&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListSearchBy=columnView&ControlGroupSearchView%24ButtonSubmit=T%C3%ACm+ki%E1%BA%BFm",
                strRound,//0
                booking.FromCity,//1
                booking.ToCity,//2
                tkDepart.StartDate.ToString("dd"),//3
                tkDepart.StartDate.ToString("MM"),//4
                tkDepart.StartDate.ToString("yyyy"),//5
                strReturnDay,//6
                strReturnMonth,//7
                strReturnYear,//8
                iAdut,//9
                iChild,//10
                iBaby//11
                );
            string linkSeach = "http://booking.airasia.com/Search.aspx";
            var resSearch = m_request.PostData(linkSeach, strData);
            string htmSearch = m_request.GetHtmlFromResponse(resSearch);
            lstResultHTML[linkSeach] = htmSearch;
            this.GetRealData(htmSearch);
            DateTime? dtNull = null;

            List<BK_Ticket> lstTicket = GetFromHTML(htmSearch, booking.FromCity, booking.ToCity, tkDepart.StartDate, tkReturn != null ? tkReturn.StartDate : dtNull, iAdut, iChild, iBaby, _iUserID);

            #endregion

            #region 3.Select tickets

            string strBook1 = "";
            string strBook2 = "";
            //04/09/2014 18:45
            var TicketTemp = lstTicket.Where(m => m.TypeWay.ToLower() == "out" && m.DataToBook.IndexOf(tkDepart.StartDate.ToString("MM/dd/yyyy HH:mm")) > -1).SingleOrDefault();
            if (TicketTemp != null)
                strBook1 = TicketTemp.DataToBook;
            if (strBook1 == "")
            {
                this.SaveHTML(booking, lstResultHTML);
                throw new Exception("Asia: Không tìm dc vé 1");
            }
            if (tkReturn != null)
            {
                TicketTemp = lstTicket.Where(m => m.TypeWay.ToLower() == "in" && m.DataToBook.IndexOf(tkReturn.StartDate.ToString("MM/dd/yyyy HH:mm")) > -1).SingleOrDefault();
                strBook2 = TicketTemp.DataToBook;
                if (strBook2 == "")
                {
                    this.SaveHTML(booking, lstResultHTML);
                    throw new Exception("Asia: Không tìm dc vé 2");
                }
            }

            var strDataSelect = string.Format("__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFP0NvbnRyb2xHcm91cFNlbGVjdFZpZXckU3BlY2lhbE5lZWRzSW5wdXRTZWxlY3RWaWV3JENoZWNrQm94U1NSc2KF%2B3FBQndP4mQD4nrPT4PNXNaR&pageToken=&MemberLoginSelectView%24HFTimeZone=420&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24RadioButtonMarketStructure={0}&ControlGroupAvailabilitySearchInputSelectView_AvailabilitySearchInputSelectVieworiginStation1={1}&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24TextBoxMarketOrigin1={1}&ControlGroupAvailabilitySearchInputSelectView_AvailabilitySearchInputSelectViewdestinationStation1={2}&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24TextBoxMarketDestination1={2}&date_picker={4}%2F{3}%2F{5}&date_picker=&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListMarketDay1={3}&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListMarketMonth1={5}-{4}&date_picker={7}%2F{6}%2F{8}&date_picker=&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListMarketDay2={6}&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListMarketMonth2={8}-{7}&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListPassengerType_ADT={9}&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListPassengerType_CHD={10}&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListPassengerType_INFANT={11}&ControlGroupAvailabilitySearchInputSelectView%24MultiCurrencyConversionViewSelectView%24DropDownListCurrency=" + strCurrency + "&ControlGroupAvailabilitySearchInputSelectView%24AvailabilitySearchInputSelectView%24DropDownListSearchBy=columnView&ControlGroupSelectView%24AvailabilityInputSelectView%24HiddenFieldTabIndex1=4&ControlGroupSelectView%24AvailabilityInputSelectView%24market1={12}&ControlGroupSelectView%24AvailabilityInputSelectView%24HiddenFieldTabIndex2=4&{13}ControlGroupSelectView%24SpecialNeedsInputSelectView%24RadioButtonWCHYESNO=RadioButtonWCHNO&ControlGroupSelectView%24ButtonSubmit=Ti%E1%BA%BFp+t%E1%BB%A5c",
                strRound,//0
                booking.FromCity,//1
                booking.ToCity,//2
                tkDepart.StartDate.ToString("dd"),//3
                tkDepart.StartDate.ToString("MM"),//4
                tkDepart.StartDate.ToString("yyyy"),//5
                strReturnDay,//6
                strReturnMonth,//7
                strReturnYear,//8
                iAdut,//9
                iChild,//10
                iBaby,//11
                HttpUtility.UrlEncode(strBook1),//12 
                tkReturn != null ? string.Format("ControlGroupSelectView%24AvailabilityInputSelectView%24market2={0}&", HttpUtility.UrlEncode(strBook2)) : ""//13
                );
            string LinkSelect = "http://booking.airasia.com/Select.aspx";
            var resSelect = m_request.PostData(LinkSelect, strDataSelect);
            string htmSelect = m_request.GetHtmlFromResponse(resSelect);
            lstResultHTML[LinkSelect] = htmSelect;
            this.GetRealData(htmSelect);

            if (htmSelect.IndexOf("Contact details") == -1)
            {
                this.SaveHTML(booking, lstResultHTML);
                throw new Exception("asia: Không thể tới trang thông tin khách hàng");
            }

            if (htmSelect.IndexOf("[1018:ClassNotAvailable]") > -1)
            {
                this.SaveHTML(booking, lstResultHTML);
                throw new Exception("Không tìm dc ghế ngồi");
            }

            #endregion

            #region 4.Travel infomation

            var paramSelects = HtmlHelper.GetFormData(htmSelect, "//*[@id=\"SkySales\"]");

            HtmlHelper.UpdateFormData(paramSelects, "__VIEWSTATE", viewstate);
            //__EVENTTARGET
            HtmlHelper.UpdateFormData(paramSelects, "__EVENTTARGET", "");

            paramSelects = HtmlHelper.UpdateFormData(paramSelects, "BaggageLegInputViewTravelerView", "");// cập nhật hành lí

            #region Add Baggage


            //CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$BaggageLegInputViewTravelerView$SsrQuantity_passengerNumber_0_journey_1_flightReference_20140730-FD-651-SGNDMK
            htmSelect = htmSelect.Replace("value class", "value=\"\" class");
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmSelect);
            var lst = doc.DocumentNode.SelectNodes("//*[@class=\"baggageContainer\"]//select");

            foreach (var item in lst)
            {
                int iPassenger = 0, iJourney = 0;
                string strName = item.Attributes["name"].Value;

                string strTempSub = "passengerNumber_";
                int iStart = strName.IndexOf(strTempSub) + strTempSub.Length;
                strTempSub = strName.Substring(iStart, 1);
                iPassenger = Int32.Parse(strTempSub);

                strTempSub = "journey_";
                iStart = strName.IndexOf(strTempSub) + strTempSub.Length;
                strTempSub = strName.Substring(iStart, 1);
                iJourney = Int32.Parse(strTempSub);

                string iBG = iJourney == 1 ? passenges[iPassenger].BaggageDepartValue.ToString() : passenges[iPassenger].BaggageReturnValue.ToString();

                if (isBackReturnToDepart)
                {
                    iBG = passenges[iPassenger].BaggageReturnValue.ToString();
                }

                switch (iBG)
                {
                    case "20":
                        iBG = "PBAB";
                        break;
                    case "25":
                        iBG = "PBAC";
                        break;
                    case "30":
                        iBG = "PBAD";
                        break;
                    case "40":
                        iBG = "PBAF";
                        break;
                    default:
                        iBG = "";
                        break;
                }
                string strBg = "";
                if (iBG != "")
                {
                    strBg = strName.Replace("CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$BaggageLegInputViewTravelerView$", "");
                    strBg = strBg.Replace("_journey_" + iJourney, "_ssrCode_" + iBG + "_ssrNum_" + iJourney);
                }
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, strName, strBg);// cập nhật hành lí

                iPassenger++;
            }

            #endregion

            paramSelects = HtmlHelper.DeleteFormData(paramSelects, "CheckBoxImFlying");//xoá box i'm fly
            //cập nhật quốc gia
            //CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$PassengerInputTravelerView$DropDownListNationality_
            paramSelects = HtmlHelper.UpdateFormData(paramSelects, "DropDownListNationality", "VN");

            paramSelects = HtmlHelper.DeleteFormData(paramSelects, "NextButton");
            paramSelects = HtmlHelper.DeleteFormData(paramSelects, "CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$TuneTalkInputTravelerView$CheckBoxTuneTalk");
            paramSelects = HtmlHelper.DeleteFormData(paramSelects, "CONTROLGROUP_OUTERTRAVELER$CONTROLGROUPTRAVELER$RedCarpetInputTravelerView$SsrQuantity_passengerNumber_0_ssrCode_PVIP_ssrNum");

            int index = 0;
            foreach (var item in passenges)
            {
                //cập nhật giới tính
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, "DropDownListTitle_" + index, item.Sex == "M" ? "MR" : "MS");
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, "DropDownListGender_" + index, item.Sex == "M" ? "1" : "2");//DropDownListGender_0
                //Cập nhật tên
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, "TextBoxFirstName_" + index, item.Name);
                //cập nhật họ
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, "TextBoxLastName_" + index, item.FirstName);
                //cập nhật ngày sinh
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, "DropDownListBirthDateDay_" + index, item.Birthday.ToString("%d"));
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, "DropDownListBirthDateMonth_" + index, item.Birthday.ToString("%M"));
                paramSelects = HtmlHelper.UpdateFormData(paramSelects, "DropDownListBirthDateYear_" + index, item.Birthday.ToString("yyyy"));
                //
                index++;
            }


            string strDataTravel = "";

            strDataTravel = HtmlHelper.GenFormData(paramSelects);
            //strDataTravel += "&checkBoxInsuranceName=InsuranceInputControlAddOnsViewAjax%24CheckBoxInsuranceAccept&checkBoxInsuranceId=CONTROLGROUP_InsuranceInputControlAddOnsViewAjax_CheckBoxInsuranceAccept&checkBoxAUSNoInsuranceId=InsuranceInputControlAddOnsViewAjax_CheckBoxAUSNo&declineInsuranceLinkButtonId=InsuranceInputControlAddOnsViewAjax_LinkButtonInsuranceDecline&insuranceLinkCancelId=InsuranceInputControlAddOnsViewAjax_LinkButtonInsuranceDecline&radioButtonNoInsuranceId=InsuranceInputControlAddOnsViewAjax_RadioButtonNoInsurance&radioButtonYesInsuranceId=InsuranceInputControlAddOnsViewAjax_RadioButtonYesInsurance";
            //string strEnsure = "&checkBoxInsuranceName=InsuranceInputControlAddOnsViewAjax%24CheckBoxInsuranceAccept&checkBoxInsuranceId=CONTROLGROUP_InsuranceInputControlAddOnsViewAjax_CheckBoxInsuranceAccept&checkBoxAUSNoInsuranceId=InsuranceInputControlAddOnsViewAjax_CheckBoxAUSNo&declineInsuranceLinkButtonId=InsuranceInputControlAddOnsViewAjax_LinkButtonInsuranceDecline&insuranceLinkCancelId=InsuranceInputControlAddOnsViewAjax_LinkButtonInsuranceDecline&radioButtonNoInsuranceId=InsuranceInputControlAddOnsViewAjax_RadioButtonNoInsurance&radioButtonYesInsuranceId=InsuranceInputControlAddOnsViewAjax_RadioButtonYesInsurance&radioButton=on&CONTROLGROUP_OUTERTRAVELER%24CONTROLGROUPTRAVELER%24ButtonSubmit=Ti%E1%BA%BFp+t%E1%BB%A5c";
            //strDataTravel+=strEnsure;
            string LinkTravel = "https://booking.airasia.com/Traveler.aspx";
            var resTravel = m_request.PostData(LinkTravel, strDataTravel);
            string htmTravel = m_request.GetHtmlFromResponse(resTravel);
            lstResultHTML[LinkTravel] = htmTravel;
            this.GetRealData(htmTravel);

            //Pick A Seat
            if (htmTravel.IndexOf("Pick A Seat") == -1)
            {
                this.SaveHTML(booking, lstResultHTML);
                throw new Exception("asia: Không thể tới trang chọn chỗ");
            }

            #endregion

            #region 5.Select Map


            string strDataMap = string.Format("__EVENTTARGET=ControlGroupUnitMapView%24UnitMapViewControl%24LinkButtonAssignUnit&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUBMGRktapVDbdzjtpmxtfJuRZPDMU9XYk%3D&pageToken=&MemberLoginUnitMapView%24HFTimeZone=420&ControlGroupUnitMapView%24UnitMapViewControl%24compartmentDesignatorInput=&ControlGroupUnitMapView%24UnitMapViewControl%24deckDesignatorInput=1&ControlGroupUnitMapView%24UnitMapViewControl%24tripInput=0&ControlGroupUnitMapView%24UnitMapViewControl%24passengerInput=0&ControlGroupUnitMapView%24UnitMapViewControl%24HiddenEquipmentConfiguration_0_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_0_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_0_PassengerNumber_0_HiddenFee=NaN&ControlGroupUnitMapView%24UnitMapViewControl%24HiddenEquipmentConfiguration_1_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_1_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_1_PassengerNumber_0_HiddenFee=NaN&ControlGroupUnitMapView%24UnitMapViewControl%24HiddenEquipmentConfiguration_2_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_2_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_2_PassengerNumber_0_HiddenFee=NaN&ControlGroupUnitMapView%24UnitMapViewControl%24HiddenEquipmentConfiguration_3_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_3_PassengerNumber_0=&ControlGroupUnitMapView%24UnitMapViewControl%24EquipmentConfiguration_3_PassengerNumber_0_HiddenFee=NaN&HiddenFieldPageBookingData={0}", HttpUtility.UrlEncode(HidenData));

            string LinkMap = "https://booking.airasia.com/UnitMap.aspx";
            var resMap = m_request.PostData("https://booking.airasia.com/UnitMap.aspx", strDataMap);
            string htmMap = m_request.GetHtmlFromResponse(resMap);
            lstResultHTML[LinkMap] = htmMap;
            this.GetRealData(htmMap);

            //Review and pay
            if (htmMap.IndexOf("Review and pay") == -1)
            {
                this.SaveHTML(booking, lstResultHTML);
                throw new Exception("asia: Không thể tới review vé");
            }

            #endregion

            HtmlAgilityPack.HtmlDocument docCC = new HtmlDocument();
            docCC.LoadHtml(htmMap);

            string MCCOriginCountry = docCC.DocumentNode.SelectSingleNode("//*[@id=\"MCCOriginCountry\"]").Attributes["value"].Value;

            isCanPayLater = htmMap.IndexOf("PayLater") > -1;


            if (isCanPayLater)
            {
                #region 6.Payment for ATM

                //select Payment Later
                //string strDataPayment = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" + HttpUtility.UrlEncode(viewstate) + "&pageToken=&MemberLoginPaymentView%24HFTimeZone=420&eventTarget=&eventArgument=&viewState=" + HttpUtility.UrlEncode(viewstate)+ "&pageToken=&PriceDisplayPaymentView%24CheckBoxTermAndConditionConfirm=on&CONTROLGROUPPAYMENTBOTTOM%24MultiCurrencyConversionViewPaymentView%24DropDownListCurrency=" + strCurrency + "&MCCOriginCountry=VN&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24RadioButtonCounterPayment=RadioButtonCounterPayment_VL-VL&CONTROLGROUPPAYMENTBOTTOM%24ButtonSubmit=Submit+payment&HiddenFieldPageBookingData=" + HttpUtility.UrlEncode(HidenData);
                LogManager.GetInstance().Info("Payment for ATM");

                string strDataPayment = "__EVENTTARGET=CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView";
                strDataPayment += "&__EVENTARGUMENT=CounterPayment";
                strDataPayment += "&__VIEWSTATE=" + HttpUtility.UrlEncode(viewstate);
                strDataPayment += "&pageToken=";
                strDataPayment += "&MemberLoginPaymentView%24HFTimeZone=420";
                strDataPayment += "&eventTarget=";
                strDataPayment += "&eventArgument=";
                strDataPayment += "&viewState=" + HttpUtility.UrlEncode(viewstate);
                strDataPayment += "&pageToken=";
                strDataPayment += "&CONTROLGROUPPAYMENTBOTTOM%24MultiCurrencyConversionViewPaymentView%24DropDownListCurrency=" + strCurrency;
                strDataPayment += "&MCCOriginCountry=" + MCCOriginCountry;
                strDataPayment += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24HiddenFieldUpdatedMCC=";
                strDataPayment += "&HiddenFieldPageBookingData=" + HttpUtility.UrlEncode(HidenData);

                string LinkPay = "https://booking.airasia.com/Payment.aspx";
                var resPayment = m_request.PostData(LinkPay, strDataPayment);
                string htmPayment = m_request.GetHtmlFromResponse(resPayment);
                lstResultHTML[LinkPay] = htmPayment;
                this.GetRealData(htmPayment);
                //end select Payment Later

                //Payment
                string strTemp = "__EVENTTARGET=";
                strTemp += "&__EVENTARGUMENT=";
                strTemp += "&__VIEWSTATE=" + HttpUtility.UrlEncode(viewstate);
                strTemp += "&pageToken=";
                strTemp += "&MemberLoginPaymentView%24HFTimeZone=420";
                strTemp += "&eventTarget=";
                strTemp += "&eventArgument=";
                strTemp += "&viewState=" + HttpUtility.UrlEncode(viewstate);
                strTemp += "&pageToken=";
                strTemp += "&PriceDisplayPaymentView%24CheckBoxTermAndConditionConfirm=on";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24MultiCurrencyConversionViewPaymentView%24DropDownListCurrency=" + strCurrency;
                strTemp += "&MCCOriginCountry=" + MCCOriginCountry;
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24RadioButtonCounterPayment=RadioButtonCounterPayment_VL-VL";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24ButtonSubmit=x%C3%A1c+nh%E1%BA%ADn+thanh+to%C3%A1n";
                strTemp += "&HiddenFieldPageBookingData=" + HttpUtility.UrlEncode(HidenData);

                resPayment = m_request.PostData(LinkPay, strTemp);
                htmPayment = m_request.GetHtmlFromResponse(resPayment);
                lstResultHTML[LinkPay] = htmPayment;
                this.GetRealData(htmPayment);
                //End Payment

                var lstDataPayment = HtmlHelper.GetFormData(htmPayment, "//*[@id=\"CounterPaymentForm\"]");
                string strLinkSumary = "https://otc.airasia.com/OverTheCounter/summary.aspx?culture=en-GB";
                string strDataSumary = HtmlHelper.GenFormData(lstDataPayment);
                var resSumary = m_request.PostData(strLinkSumary, strDataSumary);
                var htmSumary = m_request.GetHtmlFromResponse(resSumary);
                lstResultHTML[strLinkSumary] = htmSumary;

                var lstDataPayment1 = HtmlHelper.GetFormData(htmSumary, "//*[@id=\"PostForm\"]");
                string strLinkSumary1 = "https://otc.airasia.com/otc_vn/convenient-store-vn.aspx?culture=en-GB";
                string strDataSumary1 = HtmlHelper.GenFormData(lstDataPayment1);
                var resSumary1 = m_request.PostData(strLinkSumary1, strDataSumary1);
                var htmSumary1 = m_request.GetHtmlFromResponse(resSumary1);
                lstResultHTML[strLinkSumary1] = htmSumary1;

                var lstDataPayment2 = HtmlHelper.GetFormData(htmSumary1, "//*[@id=\"form1\"]");
                string strLinkSumary2 = "https://otc.airasia.com/otc_vn/convenient-store-vn.aspx?culture=en-GB";
                string strDataSumary2 = HtmlHelper.GenFormData(lstDataPayment2);
                var resSumary2 = m_request.PostData(strLinkSumary2, strDataSumary2);
                var htmSumary2 = m_request.GetHtmlFromResponse(resSumary2);
                lstResultHTML[strLinkSumary2] = htmSumary2;

                #endregion
            }
            else
            {
                #region Payment for Agent

                LogManager.GetInstance().Info("Payment for Agent");

                string LinkPay = "https://booking.airasia.com/Payment.aspx";
                if (booking.FromCity != "SGN" && booking.FromCity != "HAN" && booking.FromCity != "DAD")
                {
                    #region Change Currency
                    string strDataChangeUSD = "";
                    strDataChangeUSD += "__EVENTTARGET=&";
                    strDataChangeUSD += "__EVENTARGUMENT=&";
                    strDataChangeUSD += string.Format("__VIEWSTATE={0}&", HttpUtility.UrlEncode(viewstate));
                    strDataChangeUSD += "pageToken=&";
                    strDataChangeUSD += "MemberLoginPaymentView%24HFTimeZone=420&";
                    strDataChangeUSD += "eventTarget=&";
                    strDataChangeUSD += "eventArgument=&";
                    strDataChangeUSD += string.Format("viewState={0}&", HttpUtility.UrlEncode(viewstate));
                    strDataChangeUSD += "pageToken=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24MultiCurrencyConversionViewPaymentView%24DropDownListCurrency=5028728127&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24MultiCurrencyConversionViewPaymentView%24ButtonApplyMCC=Apply&";
                    strDataChangeUSD += "MCCOriginCountry=TH&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24CCPayment=14091419333034200&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_VI_RegisteredCC_VI14091419333034200=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListPaymentMethodCode=ExternalAccount%3AVI&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_AX=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_AX=THANH+LINH+VU&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_AX=09&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_AX=2014&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_AX=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_AX=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_AX=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_AX=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_BG=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_BG=THANH+LINH+VU&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_BG=09&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_BG=2014&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_BG=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_BG=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_BG=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_BG=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_MC=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_MC=THANH+LINH+VU&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_MC=09&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_MC=2014&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_MC=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_MC=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_MC=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_MC=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_VI=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_VI=THANH+LINH+VU&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_VI=09&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_VI=2014&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_VI=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_VI=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_VI=&";
                    strDataChangeUSD += "CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_VI=&";
                    strDataChangeUSD += string.Format("HiddenFieldPageBookingData={0}", HttpUtility.UrlEncode(HidenData));

                    var resChange = m_request.PostData(LinkPay, strDataChangeUSD);
                    var htmChange = m_request.GetHtmlFromResponse(resChange);
                    lstResultHTML[LinkPay + "ChangeCurrencys"] = htmChange;

                    #endregion
                }
                HtmlDocument docPayment = new HtmlDocument();
                docPayment.LoadHtml(htmMap);
                //
                string ccPayment = docPayment.DocumentNode.SelectNodes("//*[@id=\"CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentView_RadioButtonPaymentCC_0_VI\"]")[0].Attributes["value"].Value;


                string strTemp = "__EVENTTARGET=CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView";
                strTemp += "&__EVENTARGUMENT=Direct+Debit";
                strTemp += "&__VIEWSTATE=" + HttpUtility.UrlEncode(viewstate);
                strTemp += "&pageToken=";
                strTemp += "&MemberLoginPaymentView%24HFTimeZone=420";
                strTemp += "&eventTarget=";
                strTemp += "&eventArgument=";
                strTemp += "&viewState=" + HttpUtility.UrlEncode(viewstate);
                strTemp += "&pageToken=";
                strTemp += "&PriceDisplayPaymentView%24CheckBoxTermAndConditionConfirm=on";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24MultiCurrencyConversionViewPaymentView%24DropDownListCurrency=" + strCurrency;
                strTemp += "&MCCOriginCountry=" + MCCOriginCountry;
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24CCPayment=" + ccPayment;
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_VI_RegisteredCC_VI" + ccPayment + "=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListPaymentMethodCode=ExternalAccount%3AVI";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_AX=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_AX=THANH+LINH+VU";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_AX=08";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_AX=2014";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_AX=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_AX=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_AX=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_AX=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_BG=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_BG=THANH+LINH+VU";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_BG=08";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_BG=2014";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_BG=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_BG=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_BG=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_BG=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_MC=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_MC=THANH+LINH+VU";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_MC=08";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_MC=2014";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_MC=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_MC=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_MC=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_MC=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxACCTNO_VI=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__AccountHolderName_VI=THANH+LINH+VU";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Month_VI=08";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24DropDownListEXPDAT_Year_VI=2014";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxCC__VerificationCode_VI=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSNAME_VI=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM_PaymentInputViewPaymentViewIssuingCountry_VI=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24TextBoxISSCTRY_VI=";
                strTemp += "&HiddenFieldPageBookingData=" + HttpUtility.UrlEncode(HidenData);

                var resPayment = m_request.PostData(LinkPay, strTemp);
                var htmPayment = m_request.GetHtmlFromResponse(resPayment);
                lstResultHTML[LinkPay + "1"] = htmPayment;

                this.GetRealData(htmPayment);


                strTemp = "__EVENTTARGET=";
                strTemp += "&__EVENTARGUMENT=";
                strTemp += "&__VIEWSTATE=" + HttpUtility.UrlEncode(viewstate);
                strTemp += "&pageToken=";
                strTemp += "&MemberLoginPaymentView%24HFTimeZone=420";
                strTemp += "&eventTarget=";
                strTemp += "&eventArgument=";
                strTemp += "&viewState=" + HttpUtility.UrlEncode(viewstate);
                strTemp += "&pageToken=";
                strTemp += "&PriceDisplayPaymentView%24CheckBoxTermAndConditionConfirm=on";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24MultiCurrencyConversionViewPaymentView%24DropDownListCurrency=" + strCurrency;
                strTemp += "&MCCOriginCountry=" + MCCOriginCountry;
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24HiddenFieldUpdatedMCC=";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24PaymentInputViewPaymentView%24RadioButtonDirectDebit=RadioButton_Smartlink-Smartlink";
                strTemp += "&CONTROLGROUPPAYMENTBOTTOM%24ButtonSubmit=x%C3%A1c+nh%E1%BA%ADn+thanh+to%C3%A1n";
                strTemp += "&HiddenFieldPageBookingData=" + HttpUtility.UrlEncode(HidenData);

                resPayment = m_request.PostData(LinkPay, strTemp);
                htmPayment = m_request.GetHtmlFromResponse(resPayment);
                lstResultHTML[LinkPay + "2"] = htmPayment;
                this.GetRealData(htmPayment);
                //End Payment



                #endregion
            }

            if (HidenData.Length == 6)
            {
                //this.SaveHTML(booking, lstResultHTML);
                return (int)BookingStatus.BOOKED;
            }
            else
                this.SaveHTML(booking, lstResultHTML);

            return (int)BookingStatus.UNKNOW;// đặt chỗ khong thành công

        }

        private void SaveHTML(BK_Booking booking, Dictionary<string, string> lstResultHTML)
        {
            int index = 1;
            foreach (var item in lstResultHTML)
            {
                FileHelper.WriteFile(item.Value, "BookingLogFiles", "ERROR_ASIA_" + DateTime.Now.ToString("dd_MM_HH_mm_") + booking.Phone + "_" + index + item.Key + ".html");
                index++;
            }
        }

        public decimal GetOutputFee(decimal TotalPrice, DateTime StartDate)
        {
            #region 0.Get fee

            return 0;
            #endregion
        }


    }
}
